package com.example.mallcommon;

import com.example.mallcommon.constant.ResponseCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;

/** @author yang 结果状态 ,正常响应200，其他状态码都为失败 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
@ApiModel("api通用返回数据")
public class RestResult<T> implements Serializable {
  private static final long serialVersionUID = 7498483649536881777L;

  @ApiModelProperty("返回错误码")
  private int code;

  @ApiModelProperty("提示信息,供报错时使用")
  private String message;

  @ApiModelProperty("返回的数据")
  private T data;

  @ApiModelProperty("标识代码,true表示成功，false表示出错")
  private boolean success;

  @ApiModelProperty("返回时间戳")
  private long timestamp;

  public static <T> RestResult<T> success() {
    return restResult(null, ResponseCode.SUCCESS.getCode(), null, true);
  }

  public static <T> RestResult<T> success(T data) {
    return restResult(data, ResponseCode.SUCCESS.getCode(), null, true);
  }

  public static <T> RestResult<T> success(T data, String msg) {
    return restResult(data, ResponseCode.SUCCESS.getCode(), msg, true);
  }

  public static <T> RestResult<T> failed() {
    return restResult(null, ResponseCode.ERROR.getCode(), null, false);
  }

  public static <T> RestResult<T> failed(String msg) {
    return restResult(null, ResponseCode.ERROR.getCode(), msg, false);
  }

  public static <T> RestResult<T> failed(String msg,int code) {
    return restResult(null, ResponseCode.ERROR.getCode(), msg, false);
  }

  public static <T> RestResult<T> failed(T data) {
    return restResult(data, ResponseCode.ERROR.getCode(), null, false);
  }

  public static <T> RestResult<T> failed(T data, String msg) {
    return restResult(data, ResponseCode.ERROR.getCode(), msg, false);
  }

  private static <T> RestResult<T> restResult(T data, int code, String message, boolean success) {
    RestResult<T> apiResult = new RestResult<>();
    apiResult.setData(data);
    apiResult.setCode(code);
    apiResult.setMessage(message);
    apiResult.success = success;
    apiResult.timestamp = System.currentTimeMillis();
    return apiResult;
  }

  public RestResult(T data) {
    this.data = data;
    this.success = true;
    this.code = ResponseCode.SUCCESS.getCode();
    this.message = ResponseCode.SUCCESS.getDesc();
    this.timestamp = System.currentTimeMillis();
  }

  public static RestResult custom(String message){
      return restResult(message, ResponseCode.SUCCESS.getCode(), message, true);
  }
}
